import { request as umiRequest } from '@umijs/max';
import { message } from 'antd';
import saveAs from 'file-saver';

export interface IRes<T> {
  code: number;
  message: string;
  data?: T;
}

export interface IResList<T> {
  code: number;
  message: string;
  data?: {
    pageData?: T[];
    pagedInfo?: {
      page: number;
      size: number;
      total: number;
    };
  };
}

export interface IPageParams {
  page?: number;
  size?: number;
}
export interface IResponse<T = null> extends Promise<IRes<T>> {}
export interface IResponseList<T> extends Promise<IResList<T>> {}

const reParamSplit = /\s*;\s*/;
const reHeaderSplit = /\s*:\s*/;
const rePropertySplit = /\s*=\s*(.+)/;
const reEncodingSplit = /\s*'[^']*'\s*(.*)/;
const reQuotesTrim = /(?:^["'\s]*)|(?:["'\s]*$)/g;

export const parseContentDisposition = (
  data: string,
):
  | { encoding?: string; name?: string; filename: string; type: string }
  | undefined => {
  if (!data) {
    return;
  }
  const headerSplit = data
    .split(reParamSplit)
    .map((item) => decodeURIComponent(item.trim()))
    .filter((item) => !!item);

  let type = headerSplit.shift();
  if (!type) {
    return;
  }
  const split = type.toLowerCase().split(reHeaderSplit);
  type = split[1] || split[0];

  return headerSplit
    .map((prop) => prop.split(rePropertySplit))
    .reduce(
      (o: any, [key, value]) => {
        if (!value) {
          o[key] = true;
        } else if (key.slice(-1) === '*') {
          let encoding;
          [encoding, value] = value.split(reEncodingSplit);
          if (value) {
            try {
              value = decodeURIComponent(value);
            } catch (e) {}
            o[key.slice(0, -1).toLowerCase()] = value;
          }
          o.encoding = encoding.toLowerCase();
        } else if (!(key in o)) {
          o[key.toLowerCase()] = value.replace(reQuotesTrim, '');
        }
        return o;
      },
      { type },
    );
};

export const download = async (req: () => Promise<any>) => {
  const res = await req();
  if (res.data && res.headers['content-disposition']) {
    saveAs(
      res.data,
      parseContentDisposition(res.headers['content-disposition'])?.filename,
    );
  } else {
    let msg = '下载失败';
    try {
      const data = JSON.parse((await res.data?.text()) || '');
      msg = data?.message;
    } catch (e) {}
    message.error(msg);
  }
};

export const request1 = umiRequest;
